package com.sqllog.admin.auth.controller;

import com.github.pagehelper.PageInfo;
import com.sqllog.admin.auth.domain.EditPassword;
import com.sqllog.admin.auth.domain.User;
import com.sqllog.admin.auth.domain.response.Result;
import com.sqllog.admin.auth.domain.response.module.ResultTable;
import com.sqllog.admin.auth.service.UserService;
import com.sqllog.admin.framework.controller.ResultController;
import com.sqllog.admin.framework.domain.request.PageDomain;
import com.sqllog.admin.framework.tools.SecurityUtil;
import com.sqllog.admin.framework.tools.SequenceUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;


/**
 *  用 户 控 制 器
 *
 * @author chennengcheng
 * @date 2022-01-21 17:02
 * @remark
 */

@RestController
@RequestMapping(SysMenuController.API_SYSTEM_PREFIX + "user")
public class SysUserController extends ResultController {

    /**
     * Describe: 基础路径
     */
    private static String MODULE_PATH = "system/user/";

    /**
     * Describe: 用户模块服务
     */
    @Resource
    private UserService sysUserService;

    /**
     * 获取用户列表视图
     * @return
     */
    @GetMapping("main")
    public ModelAndView main() {
        return jumpPage(MODULE_PATH + "main");
    }

    /**
     * 获取用户列表数据
     * @param pageDomain
     * @param param
     * @return
     */
    @GetMapping("data")
    public ResultTable data(PageDomain pageDomain, User param) {
        PageInfo<User> pageInfo = sysUserService.page(param, pageDomain);
        return pageTable(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 用户新增接口
     * @param sysUser
     * @return
     */
    @PostMapping("save")
    public Result save(@RequestBody User sysUser) {
        sysUser.setLogin("0");
        sysUser.setEnable("1");
        sysUser.setStatus("1");
        sysUser.setUserId(SequenceUtil.makeStringId());
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        Boolean result = sysUserService.save(sysUser);
        return decide(result);
    }

    /**
     * 用户修改视图
     * @param model
     * @param userId
     * @return
     */
    @GetMapping("edit")
    public ModelAndView edit(Model model, String userId) {
        model.addAttribute("sysUser", sysUserService.getById(userId));
        return jumpPage(MODULE_PATH + "edit");
    }

    /**
     * 用户密码修改视图
     * @param model
     * @param userId
     * @return
     */
    @GetMapping("editpasswordadmin")
    public ModelAndView editPasswordAdminView(Model model, String userId) {
        model.addAttribute("userId", userId);
        return jumpPage(MODULE_PATH + "editPasswordAdmin");
    }

    /**
     * 管理员修改用户密码接口
     * @param editPassword
     * @return
     */
    @PutMapping("editPasswordAdmin")
    public Result editPasswordAdmin(@RequestBody EditPassword editPassword) {
        User editUser = sysUserService.getById(editPassword.getUserId());
        editUser.setPassword(new BCryptPasswordEncoder().encode(editPassword.getNewPassword()));
        boolean result = sysUserService.update(editUser);
        return decide(result, "修改成功", "修改失败");
    }

    /**
     * 用户密码修改视图
     * @return
     */
    @GetMapping("editPassword")
    public ModelAndView editPasswordView() {
        return jumpPage(MODULE_PATH + "password");
    }

    /**
     * 用户密码修改接口
     * @param editPassword
     * @return
     */
    @PutMapping("editPassword")
    public Result editPassword(@RequestBody EditPassword editPassword) {
        String oldPassword = editPassword.getOldPassword();
        String newPassword = editPassword.getNewPassword();
        String confirmPassword = editPassword.getConfirmPassword();
        User sysUser = SecurityUtil.currentUser();
        User editUser = sysUserService.getById(sysUser.getUserId());
        if (Strings.isBlank(confirmPassword)
                || Strings.isBlank(newPassword)
                || Strings.isBlank(oldPassword)) {
            return failure("输入不能为空");
        }
        if (!new BCryptPasswordEncoder().matches(oldPassword, editUser.getPassword())) {
            return failure("密码验证失败");
        }
        if (!newPassword.equals(confirmPassword)) {
            return failure("两次密码输入不一致");
        }
        editUser.setPassword(new BCryptPasswordEncoder().encode(newPassword));
        boolean result = sysUserService.update(editUser);
        return decide(result, "修改成功", "修改失败");
    }

    /**
     * 用户修改接口
     * @param sysUser
     * @return
     */
    @PutMapping("update")
    public Result update(@RequestBody User sysUser) {
        boolean result = sysUserService.update(sysUser);
        return decide(result);
    }

    /**
     * 头像修改接口
     * @param sysUser
     * @return
     */
    @PutMapping("updateAvatar")
    public Result updateAvatar(@RequestBody User sysUser) {
        String userId = SecurityUtil.currentUser().getUserId();
        sysUser.setUserId(userId);
        boolean result = sysUserService.update(sysUser);
        return decide(result);
    }

    /**
     * 用户批量删除接口
     * @param ids
     * @return
     */
    @DeleteMapping("batchRemove/{ids}")
    public Result batchRemove(@PathVariable String ids) {
        boolean result = sysUserService.batchRemove(ids.split(","));
        return decide(result);
    }

    /**
     * 用户删除接口
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable String id) {
        boolean result = sysUserService.remove(id);
        return decide(result);
    }


    /**
     * 根据 userId 开启用户
     * @param sysUser
     * @return
     */
    @PutMapping("enable")
    public Result enable(@RequestBody User sysUser) {
        sysUser.setEnable("1");
        boolean result = sysUserService.update(sysUser);
        return decide(result);
    }

    /**
     * 根据 userId 禁用用户
     * @param sysUser
     * @return
     */
    @PutMapping("disable")
    public Result disable(@RequestBody User sysUser) {
        sysUser.setEnable("0");
        boolean result = sysUserService.update(sysUser);
        return decide(result);
    }

    /**
     * 个人资料
     * @param model
     * @return
     */
    @GetMapping("center")
    public ModelAndView center(Model model) {
        User sysUser = SecurityUtil.currentUser();
        model.addAttribute("userInfo", sysUserService.getById(sysUser.getUserId()));
        return jumpPage(MODULE_PATH + "center");
    }

    /**
     * 用户修改接口
     * @param sysUser
     * @return
     */
    @PutMapping("updateInfo")
    public Result updateInfo(@RequestBody User sysUser) {
        boolean result = sysUserService.update(sysUser);
        return decide(result);
    }

}
